package chapter7;

/**
 * 在其他数都出现k次的数组中找到只出现一次的数
 */
public class OnceNum {
    public static int onceNum(int[] arr, int k){
        int[] eO = new int[32];
        // k个k进制的数按位无进位相加等于0
        for (int anArr : arr) {
            help(eO, anArr, k);
        }
        return getNumFromKsysNum(eO, k);
    }

    // 将value转化为k进制，按位无进位加进eO数组
    private static void help(int[] eO, int value, int k) {
        int[] cur = getKsysNum(value, k);
        for (int i = 0; i < cur.length; i++) {
            eO[i] = (eO[i] + cur[i]) % k;
        }
    }
    // 转化为k进制，从低位到高位保存到res中
    private static int[] getKsysNum(int value, int k) {
        int[] res = new int[32];
        int index = 0;
        while (value != 0) {
            res[index++] = value % k;
            value /= k;
        }
        return res;
    }

    // 将k进制转化为十进制
    private static int getNumFromKsysNum(int[] eO, int k) {
        int res = 0;
        for (int i = eO.length - 1; i >= 0; i--) {
            res = res * k + eO[i];
        }
        return res;
    }


}
